# -*- coding: utf-8 -*-
from kivy.app import App
from kivy.clock import Clock
from kivy.core.audio import SoundLoader

from kivy.properties import NumericProperty
import model.gamestate
from ui.hat_widget import HatWidget


class BeforeRoundScreen(HatWidget):
    timeout = NumericProperty()
    progress = NumericProperty()

    def __init__(self, gamestate, presenter, **kwargs):
        """ Construct BeforeRound screen
        """
        super(BeforeRoundScreen, self).__init__(**kwargs)
        self.presenter = presenter
        self.gamestate = gamestate
        self.timeout = presenter.settings.game.countdown_time_sec + 1
        Clock.schedule_interval(self.update, min(1, self.timeout / 15))
        self.short_sound = SoundLoader.load('data/short_sound.wav')
        self.long_sound = SoundLoader.load('data/long_sound.wav')
        self.prev_sound_time_sec = 1000
        self.sound_on = presenter.settings.sound.get_property('sound_on')
        self.play_sound()

    def update(self, dt):
        self.timeout = self.timeout - dt
        max_timeout = self.gamestate.settings.time_before_out_sec + 1
        self.progress = 1 - (self.timeout / (max_timeout))
        if (int(self.timeout) <= 0):
            """change phase to BEFORE_ROUND
            after gamestate.settings.time_before_out_sec seconds
            """
            self.presenter.change_phase(model.gamestate.Phase.GUESS_WORD)
            return False
        self.play_sound()

    def play_sound(self):
        if (self.sound_on) and \
                (self.prev_sound_time_sec - self.timeout > 0.95):
            if (self.timeout > 1.4 + self.long_sound.length):
                self.prev_sound_time_sec = self.timeout
                self.short_sound.play()
            else:
                self.prev_sound_time_sec = 0
                self.long_sound.play()


class BeforeRoundScreenApp(App):
    def build(self):
        screen = BeforeRoundScreen(None, None)
        return screen


if __name__ == '__main__':
    BeforeRoundScreenApp().run()
